package org.ct.utils;

import java.util.List;

import org.ct.Globals;
import org.ct.dataobjects.Student;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;

public class HibernateUtils {
	public static void addNewStudent(Student student) {
		Session session = Globals.hibSessionFactory.openSession();
		session.beginTransaction();
		session.save(student);
		session.getTransaction().commit();
		session.close();
	}

	public static List<? extends Student> selectAllStudents() {
		Session session = Globals.hibSessionFactory.openSession();
		session.beginTransaction();

		Criteria criteria = session.createCriteria(Student.class);
		List<? extends Student> result = criteria.list();

		session.getTransaction().commit();
		session.close();

		return result;
	}

	public static Student getById(Integer id) {

		Session session = Globals.hibSessionFactory.openSession();
		session.beginTransaction();

		Criteria criteria = session.createCriteria(Student.class);
		criteria.add(Restrictions.idEq(id));
		Student student = (Student) criteria.uniqueResult();

		session.getTransaction().commit();
		session.close();

		return student;
	}

	public static void addNewStudentWithIdCollisionCheck(Student student) throws IllegalArgumentException {

		if (student == null) throw new IllegalArgumentException("Student cannot be null");
		Integer id;
		if ((id = student.getId()) == null) throw new IllegalArgumentException("Student id cannot be null");

		Session session = Globals.hibSessionFactory.openSession();
		session.beginTransaction();

		Criteria criteria = session.createCriteria(Student.class);
		criteria.add(Restrictions.idEq(id));
		Student studentExisting = (Student) criteria.uniqueResult();

		if (studentExisting == null) {
			session.save(student);
			session.getTransaction().commit();
		} else {
			throw new IllegalArgumentException("Student exists with given id");
		}

		session.close();
	}
}
